// @import
import CdTimer from "../util/CdTimer";
import MsgBus from "./MsgBus";
import MyCoroutine from "../base/MyCoroutine";

// @const
const { ccclass } = cc._decorator;

/**
 * 消息总线助手
 */
@ccclass
export default class MsgBusHelper extends cc.Component {
    /**
     * 断线检查 Cd 时间
     */
    _nDisconnCheckCdTime: number = 0;

    /**
     * start
     */
    start(): void {
        let oURL = new URL(window.location.href);
        
        let strServerAddr: string = oURL.searchParams.get("serverAddr");
        let xUseSSL: boolean = ("1" == oURL.searchParams.get("SSL"));

        console.log("启动消息总线助手");

        // 初始化消息总线
        MsgBus.getInstance()
            .putServerAddr(strServerAddr)
            .putUseSSL(xUseSSL)
            .tryInit();

        MyCoroutine.startCoroutine(__reconnectCheck_XC());
    }

    /**
     * lateUpdate
     */
    lateUpdate(): void {
        while (MsgBus.getInstance().getMsgQLen() > 0) {
            // 获取并处理消息
            let oMsgWrapper = MsgBus.getInstance().doMsgQShift();
            __handleXResult(this, oMsgWrapper);
        }
    }
}

///////////////////////////////////////////////////////////////////////

/**
 * ( 协程方式 ) 重连检查
 */
function* __reconnectCheck_XC(): Generator<boolean> {
    // 创建等待 Cd
    let oWaitCd: CdTimer = new CdTimer();

    while (true) {
        yield* oWaitCd.fill(5).wait_XC();

        if (!MsgBus.getInstance().isReady()) {
            // 如果没有准备好,
            // 重新初始化
            MsgBus.getInstance().tryInit();
        }
    }
}

/**
 * 处理消息结果
 * 
 * @param SELF this 指针
 * @param oMsgWrapper 消息包装对象
 */
function __handleXResult(SELF: MsgBusHelper, oMsgWrapper: { _nMsgCode: number, _oMsgBody: any, }): void {
    if (null == SELF ||
        null == oMsgWrapper) {
        return;
    }

    if ("function" != typeof MsgBus.getInstance().onMsgHandler) {
        // 每次执行前都要进行检查,
        // 因为在处理消息的过程中有可能会将 onMsgHandler 设置为空...
        // 设置为空之后,
        // MsgBus 接到的消息会放置到 _oMsgQ 里,
        // 等到后续继续处理...
        return;
    }

    // 处理收到的消息
    MsgBus.getInstance().onMsgHandler(
        oMsgWrapper._nMsgCode, oMsgWrapper._oMsgBody
    );
}
